var fs = require('fs');
var path = require('path');
var async = require('async');
var glob = require('glob');


//代码压缩
var uglifyjs = require('uglify-es');
// es6 转 es5 
var babel = require('babel-core');

// css 自动加前缀
var autoprefixer = require('autoprefixer');
var postcss = require('postcss');
var zlib = require('zlib');


// 写入文件
function writeFile(src, data) {
    return new Promise(function (resolve, reject) {
        fs.writeFile(src, data, (err) => {
            if (err) {
                reject(err);
                return;
            }
            resolve(data);// 成功写入文件
        });
    });
}

//
function fileIsJs(file) {
    return path.extname(file) === '.js';
}

function fileIsCss(file) {
    return path.extname(file) === '.wxss';
}

function fileIsXml(file) {
    return path.extname(file) === '.wxml';
}

function fileIsJson(file) {
    return path.extname(file) === '.json';
}

function fileIsImage(file) {
    var ext = path.extname(file);
    return ext == '.jpg' || ext === '.jpeg' || ext === '.png' || ext === '.gif';
}

function fileNeedIgnore(file) {
    if (fileIsXml(file) || fileIsJson(file) || fileIsImage(file)) {

        return false;
    }
    return true;
}

// 打包小程序
function pack(src, dest) {
    //  return minappack(src, dest);
    return transform(src, dest);
}

function readfile(src) {
    return new Promise((resolve, reject) => {
        fs.readFile(src, function (err, code) {
            if (err) {
                reject(err);
            }
            resolve(code.toString());
        });
    });
}

function babeltransform(code, src) {
    return new Promise((resolve, reject) => {
        let file = path.resolve(__dirname, '../.babelrc');
        let babelresult = babel.transform(code, { presets: ['es2015', 'stage-0'], babelrc: !1, 'filename': file, sourceFileName: src });
        resolve(babelresult);
    });
}

// es6 转 es5 并压缩代码
function transformJs(src) {
    return readfile(src)
        .then((filedata) => {
            return babeltransform(filedata, src);
        }).then((babelresult) => {
            //压缩js
            var uglifyjsResult = uglifyjs.minify(babelresult.code, { compress: false, mangle: true });
            if (uglifyjsResult.error) {
                throw uglifyjsResult.error;
            }
            // 写入js 
            var code = uglifyjsResult.code;

            return writeFile(src, code);
        });
}

// 转化css 自动加前缀
function transformCss(src) {
    return new Promise(function (resolve, reject) {
        fs.readFile(src, function (err, css) {
            if (err) {
                reject(err);
                return;
            }
            postcss([autoprefixer]).process(css).then(function (result) {
                return writeFile(src, result.css);
            }).then(() => {
                resolve();
            })
                .catch(error => {
                    reject(error);
                });
        });
    });
}

//转化 js wxss 压缩转化js wxss 加前缀
function transform(src, desc) {
    return new Promise(function (resolve, reject) {
        glob(`${src}/**/*`, function (err, files) {
            if (err) {
                reject(err);
            }

            async.each(files, function (file, callback) {
                if (fileIsJs(file)) {
                    transformJs(file).then(function (code) {
                        callback(null);
                    }, function (err) {
                        callback(err);
                    });
                } else if (fileIsCss(file)) {
                    transformCss(file).then(function (code) {
                        callback(null);
                    }, function (err) {
                        callback(err);
                    });
                } else {

                    if (fileNeedIgnore(file) && !fs.statSync(file).isDirectory()) { //是否不属于小程序的文件 直接删除
                        fs.unlinkSync(file);
                    }
                    callback(null);

                }


            }, function (err) {
                if (err) {
                    console.log('error data' + err);
                    reject(err);
                }
                resolve();
            });
        });
    });
}

module.exports = transform;